@echo off
chcp 65001 > nul
setlocal enabledelayedexpansion

rem 设置配置文件路径
set "CONFIG_FILE=config.ini"

rem 检查配置文件是否存在
if not exist "%CONFIG_FILE%" (
    echo 错误: 配置文件 %CONFIG_FILE% 不存在
    exit /b 1
)

rem 解析配置文件
for /f "tokens=1,2 delims==" %%a in ('type "%CONFIG_FILE%" ^| findstr /r "^SEALOS_URL="') do set "SEALOS_URL=%%b"
for /f "tokens=1,2 delims==" %%a in ('type "%CONFIG_FILE%" ^| findstr /r "^HELM_VERSION="') do set "HELM_VERSION=%%b"
for /f "tokens=1,2 delims==" %%a in ('type "%CONFIG_FILE%" ^| findstr /r "^CALICO_VERSION="') do set "CALICO_VERSION=%%b"

rem 去除变量值前后的空格
set "SEALOS_URL=%SEALOS_URL: =%"
set "HELM_VERSION=%HELM_VERSION: =%"
set "CALICO_VERSION=%CALICO_VERSION: =%"

rem 下载函数
:download_component
set "url=%~1"
for %%F in ("%url%") do set "filename=%%~nxF"

echo [INFO] 正在下载 %filename%...
echo [INFO] 下载URL: %url%

rem 检查wget是否可用
where wget >nul 2>&1
if %ERRORLEVEL% neq 0 (
    echo 错误: wget命令不可用，请先安装wget
    exit /b 1
)

rem 使用wget进行下载，支持断点续传和重试
set "retry_count=0"
:download_retry
wget --tries=1 --continue --show-progress --output-document="%filename%" "%url%"
if %ERRORLEVEL% neq 0 (
    set /a retry_count+=1
    if !retry_count! lss 3 (
        echo [WARNING] 下载失败，正在重试 (!retry_count!/3)...
        timeout /t 2 >nul
        goto download_retry
    ) else (
        echo [ERROR] 下载失败: 达到最大重试次数
        exit /b 1
    )
)

if %ERRORLEVEL% neq 0 (
    echo 错误: %filename% 下载失败
    exit /b 1
)

echo [INFO] %filename% 下载完成
exit /b 0

:main
rem 下载sealos
if defined SEALOS_URL (
    call :download_component "%SEALOS_URL%"
)

rem 可以添加其他组件的下载逻辑
rem ...

exit /b 0

:end
call :main %*